package grpc

import (
	"context"
	"encoding/json"
	. "fastdp-ops/pkg/server/api/middleware"
	"fastdp-ops/pkg/server/api/models"
	pb "fastdp-ops/proto/machine"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type Server struct {
	pb.UnimplementedMachineEnvServiceServer
}

func (s *Server) RegisterMachine(ctx context.Context, req *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	info := req.EnvInfo
	Logger.Info("信息获取结果", zap.Any("info", info))
	if info == nil || info.Info == nil {
		return &pb.RegisterResponse{Success: false, Message: "请求信息为空"}, nil
	}

	// 写入数据库：如果machine_ip已存在则更新，否则创建
	var machine models.Machines // 建议模型名用单数Machine（更符合常规）
	result := DB.Where("machine_ip = ?", info.MachineIp).First(&machine)

	// 处理数据库查询错误（非“记录不存在”的错误）
	if result.Error != nil && result.Error != gorm.ErrRecordNotFound {
		Logger.Error("查询机器信息失败", zap.Error(result.Error))
		return &pb.RegisterResponse{Success: false, Message: "查询数据库失败"}, nil
	}

	disksJSON, err := json.Marshal(info.Info.Disks)
	if err != nil {
		Logger.Error("磁盘信息序列化失败", zap.Error(err))
		return &pb.RegisterResponse{Success: false, Message: "磁盘信息格式错误"}, nil
	}

	if result.Error == gorm.ErrRecordNotFound {
		// 新agent：创建记录
		machine = models.Machines{
			MachineIP:     info.MachineIp,
			Hostname:      info.Info.Hostname,
			OSName:        info.Info.Os.Name,
			KernelVersion: info.Info.Os.Kernel,
			Arch:          info.Info.Os.Arch,
			Uptime:        info.Info.Uptime,
			CPUName:       info.Info.Cpu.Model,
			CPUCores:      int(info.Info.Cpu.Cores), // 假设Cores是int32/uint32，直接转换为int
			MemoryTotal:   int(info.Info.Memory.TotalMb),
			MemoryFree:    int(info.Info.Memory.FreeMb), // 补充int转换（假设FreeMb是数值类型）
			Disks:         json.RawMessage(disksJSON),   // 正确序列化磁盘信息
			Status:        1,
		}
		if err := DB.Create(&machine).Error; err != nil {
			Logger.Error("注册新agent失败", zap.Error(err))
			return &pb.RegisterResponse{Success: false, Message: "注册失败"}, nil
		}
	} else {
		// 已存在agent：更新信息（字段路径与创建时保持一致）
		updateData := models.Machines{
			Hostname:      info.Info.Hostname,
			OSName:        info.Info.Os.Name,
			KernelVersion: info.Info.Os.Kernel,
			Arch:          info.Info.Os.Arch,
			Uptime:        info.Info.Uptime,
			CPUName:       info.Info.Cpu.Model,
			CPUCores:      int(info.Info.Cpu.Cores),
			MemoryTotal:   int(info.Info.Memory.TotalMb),
			MemoryFree:    int(info.Info.Memory.FreeMb),
			Disks:         json.RawMessage(disksJSON),
			Status:        1,
		}
		if err := DB.Model(&machine).Updates(updateData).Error; err != nil {
			Logger.Error("更新agent信息失败", zap.Error(err))
			return &pb.RegisterResponse{Success: false, Message: "更新失败"}, nil
		}
	}

	return &pb.RegisterResponse{Success: true, Message: "注册成功"}, nil
}
